package com.rongshu.view.userInfo.activity;

import android.Manifest;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.mediaPlayer.activity.AudiobookPlayerActivity;
import com.rongshu.view.penpal.activity.PostDetailsActivity;
import com.rongshu.view.userInfo.adapter.AtMineAdapter;
import com.rongshu.view.userInfo.entity.AtMineMessage;
import com.rongshu.view.userInfo.iview.AtMineView;
import com.rongshu.view.userInfo.presenter.AtMinePresenter;
import com.utils.LogUtil;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class AtMeListActivity extends MessageListActivity<AtMinePresenter> implements AtMineView {
    //adapter
    private AtMineAdapter adapter = null;
    //map
    private Map<String, Object> map = null;
    //position
    private int position = 0;
    //intent
    private Intent intent = null;
    //@我 列表
    private List<AtMineMessage.ResponseBean> atMeList;

    @Override
    protected void initView() {
        super.initView();
        headMiddle.setText("@我");
        //set presenter
        setPresenter(new AtMinePresenter(this), this);
        //manager
        LinearLayoutManager manager = new LinearLayoutManager(this);
        //动画
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setRemoveDuration(100);
        recyclerView.setItemAnimator(defaultItemAnimator);
        //adapter
        atMeList = new ArrayList<>();
        adapter = new AtMineAdapter(this, atMeList);
        adapter.setHasStableIds(true);
        adapter.setOnItemClickListener(this);
        //recyclerview
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void requestMessage() {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getAtMyMsg(user_id,
                pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    @Override
    protected void setAllRead() {
        presenter.GetMsgAllRead();
        for (int index = 0; index < atMeList.size(); index++) {
            atMeList.get(index).setIs_read(true);
        }
        adapter.notifyDataSetChanged();
    }


    /**
     * 点击@我消息阅读
     */
    private void getSetReadAtMyMsg(int atMyMsg_id) {
        map = new HashMap<>();
        map.put("AtMyMsg_id", atMyMsg_id);
        presenter.getSetReadAtMyMsg(atMyMsg_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 删除@我的消息
     */
    private void getDeleteMsg(int obj_id) {
        map = new HashMap<>();
        map.put("obj_id", obj_id);
        map.put("type", Constant.DELETE_ATME);
        presenter.getDeleteMsg(
                (int) map.get("obj_id"),
                (int) map.get("type"),
                Common.encryptionSign(map));
        map.clear();
    }

    @Override
    public void onItemClick(int position) {
        this.position = position;
        final AtMineMessage.ResponseBean bean = atMeList.get(position);
        //标记消息已读
        if (!atMeList.get(position).isIs_read()) {
            int id = bean.getId();
            getSetReadAtMyMsg(id);
        }
        int type = bean.getType();
        //文章
        int MSG_TYPE_ARTICLE = 1;
        //连载
        int MSG_TYPE_SERIALZE = 2;
        //帖子
        int MSG_TYPE_POST = 3;
        //有声阅读
        int MSG_TYPE_AUDIOBOOK = 4;
        if (type == MSG_TYPE_ARTICLE || type == MSG_TYPE_SERIALZE) {
            //跳转到文章页面
            ArticleDetaisRequest request = new ArticleDetaisRequest();
            request.setContribute_id(bean.getObj_id());
            request.setType(5);
            request.setTopic_id(0);
            intent = new Intent(this, SingleArticleDetailsActivity.class);
            intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, request);
            startActivity(intent);
        } else if (type == MSG_TYPE_POST) {
            intent = new Intent(this, PostDetailsActivity.class);
            intent.putExtra(Constant.POST_ID, bean.getObj_id());
            intent.putExtra("showJoinIcon", true);
            startActivity(intent);
        } else if (type == MSG_TYPE_AUDIOBOOK) {
            if (XXPermissions.isHasPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW)) {
                intent = new Intent(this, AudiobookPlayerActivity.class);
                intent.putExtra(Constant.INTENT_DATA, bean.getObj_id());
                startActivity(intent);
            } else {
                XXPermissions.with(this).permission(Manifest.permission.SYSTEM_ALERT_WINDOW).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        intent = new Intent(AtMeListActivity.this, AudiobookPlayerActivity.class);
                        intent.putExtra(Constant.INTENT_DATA, bean.getObj_id());
                        startActivity(intent);
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        toast(getString(R.string.audio_book_play_permission));
                    }
                });
            }
        }
    }

    @Override
    public void onItemDeleteClick(int position) {
        AtMineMessage.ResponseBean bean = atMeList.get(position);
        getDeleteMsg(bean.getId());
        atMeList.remove(position);
        adapter.notifyItemRemoved(position);//注意这里
        adapter.notifyItemRangeChanged(position, atMeList.size() - position);//通知数据与界面重新绑定
    }

    /**
     * 头像点击
     */
    @Override
    public void onUserHeaderClick(int userIdTo) {
        int user_id = getUserId();
        if (user_id == userIdTo) {
            intent = new Intent(this, PersonDetailsActivity.class);
            startActivity(intent);
        } else {
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userIdTo);
            startActivity(intent);
        }
    }

    /**
     * @ 我信息回调
     */
    @Override
    public void onAtMyMsg(AtMineMessage mineMessage) {
        if (mineMessage != null) {
            List<AtMineMessage.ResponseBean> atMeBeans = mineMessage.getResponse();
            if (refreshLayout.isRefreshing()) {//结束刷新
                refreshLayout.finishRefresh();
            }
            if (refreshLayout.isLoading()) {//结束加载
                refreshLayout.finishLoadmore();
            }
            if (pageIndex == 1) {
                atMeList.clear();
            }
            atMeList.addAll(atMeBeans);
            adapter.notifyDataSetChanged();
            if (atMeBeans.size() == 0) {//请求不到数据，证明没有更多了
                refreshLayout.finishLoadmoreWithNoMoreData();
            }
            if (atMeList.size() == 0) {//判断显示缺省页面
                showEmptyLayout();
            } else {
                hideEmptyLayout();
            }
        }
    }

    /**
     * 点击@我消息阅读 回调
     */
    @Override
    public void onSetReadeAtMsg(INetBean bean) {
        if (bean.getErrCode() == 0) {
            messageNum--;
            if (messageNum <= 0) {
                txt_right.setVisibility(View.GONE);
            }
            atMeList.get(position).setIs_read(true);
            adapter.notifyItemChanged(position);
        } else {
            toast(bean.getErrMsg());
        }
    }
}
